package com.deltachi.lateplates;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyPlatesActivity extends ListActivity {

	private HttpPost finalDeletePlate = null;
	private DefaultHttpClient finalClient = null;

	Activity self = this;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get user account
		AccountManager mgr = AccountManager.get(getApplicationContext());
		Account[] accounts = mgr.getAccountsByType("com.google");
		Account account = accounts[0];

		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost getLatePlates = new HttpPost(
				"http://dxlateplates.appspot.com/getUserLatePlates");

		// Add your data
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userName", account.name));

		try {
			getLatePlates.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		HttpResponse resp = null;
		try {
			resp = client.execute(getLatePlates);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Get JSON String
		String jsonString = "";
		try {
			jsonString = EntityUtils.toString(resp.getEntity());
			;
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ArrayList<LatePlateData> plates = new ArrayList<LatePlateData>();
		// Create JSON object
		try {
			JSONArray jsonPlates = new JSONArray(jsonString);

			// Get plates array
			for (int i = 0; i < jsonPlates.length(); i++) {
				JSONObject plateObj = jsonPlates.getJSONObject(i);

				// Create key
				Key key;
				JSONObject keyObj = (JSONObject) plateObj.get("key");
				String kind = keyObj.getString("kind");
				int id = keyObj.getInt("id");
				key = new Key(kind, id);

				// Get fields
				String name = plateObj.getString("name");
				String userName = plateObj.getString("userName");
				String day = plateObj.getString("day");
				int type = plateObj.getInt("type");
				String comments = plateObj.getString("comments");
				int value = plateObj.getInt("value");

				// Create LatePlate
				LatePlateData plate = new LatePlateData(userName, name, day,
						type, comments);
				plate.setKey(key);

				plates.add(plate);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// Create plate display list
		ArrayList<String> plateStrings = new ArrayList<String>();
		for (LatePlateData plate : plates) {
			String meal = "";
			if (plate.getType() == 1) {
				meal = "Lunch";
			} else {
				meal = "Dinner";
			}
			String display = plate.getDay() + " " + meal + " - "
					+ plate.getComments();
			plateStrings.add(display);
		}

		String[] latePlates = new String[plateStrings.size()];
		for (int i = 0; i < plateStrings.size(); i++) {
			latePlates[i] = plateStrings.get(i);
		}
		
		if(plateStrings.size() == 0) {
			latePlates = new String[]{"You have no current late plates."};
		}

		setListAdapter(new ArrayAdapter<String>(this, R.layout.my_plates,
				latePlates));

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		final ArrayList<LatePlateData> finalPlates = (ArrayList<LatePlateData>) plates.clone();
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				if(((TextView)view).getText().toString().equalsIgnoreCase("You have no current late plates.")) {
					return;
				}
				// Delete
				finalClient = new DefaultHttpClient();
				final LatePlateData plate = finalPlates.get(position);
				HttpPost deletePlate = new HttpPost("http://dxlateplates.appspot.com/deleteLatePlate");
				
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("keyKind", plate.getKey().getKind()));
				nameValuePairs.add(new BasicNameValuePair("keyId", ""+plate.getKey().getId()));
				
				try {
					deletePlate.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					finalDeletePlate = deletePlate;
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
				AlertDialog alert = new AlertDialog.Builder(MyPlatesActivity.this)
                .setTitle("Delete late plate?")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	try {
							HttpResponse resp = finalClient.execute(finalDeletePlate);
							String type = "";
							if(plate.getType() == 1) {
								type = "lunch";
							} else {
								type = "dinner";
							}
							
							//Alert user of deletion
							Toast.makeText(getApplicationContext(), "Your " + plate.getDay() + " " + type + " late plate was deleted.", Toast.LENGTH_SHORT).show();
							onCreate(null);
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        return;
                    }
                })
                .create();
				alert.show();
			}
		});
	}

}
